package com.vimi8.ebb.auth.api;


import com.vimi8.ebb.auth.configuration.HttpResponseEntity;
import com.vimi8.ebb.auth.model.Error;
import com.vimi8.ebb.auth.model.Token;
import com.vimi8.ebb.auth.service.DBClientDetailsService;
import io.swagger.annotations.*;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.client.http.OAuth2ErrorHandler;
import org.springframework.security.oauth2.client.resource.BaseOAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.stereotype.Controller;
import org.springframework.util.Base64Utils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


@javax.annotation.Generated(value = "class io.swagger.codegen.languages.SpringCodegen", date = "2016-11-16T08:40:14.731Z")

@Controller
public class RefreshApiController implements RefreshApi {

    //@Value("${springfox.documentation.swagger.v2.host}")
    private String host="127.0.0.1";
    @Value("${server.contextPath}")
    private String contextPath;
    @Value("${server.port}")
    private String port;

    @Autowired
    private DBClientDetailsService dbClientDetailsService;

    public HttpResponseEntity<Token> refreshPost(@ApiParam(value = "refresh_token值", required = true) @RequestParam(value = "refresh_token", required = true) String refresh_token, HttpServletRequest request) {
        HttpResponseEntity<String> response=null;
        HttpHeaders responseHttpHeaders=new HttpHeaders();
        responseHttpHeaders.setContentType(MediaType.APPLICATION_JSON_UTF8);
        Error error=new Error().error("invalid_param").errorDescription("token is error.");
        Jwt jwt= JwtHelper.decode(refresh_token);
        String claims= jwt.getClaims();
        JSONObject jsonObject= JSONObject.fromObject(claims);
        if(jsonObject!=null&&jsonObject.containsKey("client_id")){
            String client_id= jsonObject.getString("client_id");
            ClientDetails clientDetails = null;
            try {
                clientDetails = dbClientDetailsService.getClientDetailsByClientId(client_id);
                if(clientDetails==null){
                    error.error("invalid_param").errorDescription("invalid client id");
                }
            } catch (Exception ex) {
                error.error("invalid_param").errorDescription(ex.getLocalizedMessage());
            }
            //检查clienid是否有效
            if (clientDetails != null) {
                RestTemplate restTemplate = new RestTemplate();
                restTemplate.setErrorHandler(new OAuth2ErrorHandler(new BaseOAuth2ProtectedResourceDetails()));
                HttpHeaders restHeader = new HttpHeaders();
                restHeader.setContentType(MediaType.APPLICATION_JSON_UTF8);
                restHeader.add("Accept", MediaType.APPLICATION_JSON_UTF8_VALUE);
                restHeader.add("Authorization", "Basic " + getBASE64(clientDetails.getClientId() + ":" + clientDetails.getClientSecret()));
                String tokenUrl = String.format("/token?grant_type=refresh_token&refresh_token=%s", refresh_token);
                tokenUrl = request.getScheme() + "://" + host + ":" + port + contextPath + tokenUrl;
                HttpEntity<Void> formEntity = new HttpEntity<Void>(restHeader);
                //logger.debug("---------tokenUrl:--------" + tokenUrl);
                Token token = restTemplate.postForObject(tokenUrl, formEntity, Token.class);
                token.setClientId(client_id);
                //logger.debug("---------token:--------" + token);
                responseHttpHeaders.add("SET-COOKIE", "Authorization=bearer%20" + token.getAccess_token() + ";expire=" + new Date((new Date().getTime()) + token.getExpires_in() * 1000) + ";path=/;HttpOnly");
                return new HttpResponseEntity<Token>(token, responseHttpHeaders, HttpStatus.OK);
            }
        }
        return new HttpResponseEntity<Token>(error,HttpStatus.BAD_REQUEST);
    }
    // 将 s 进行 BASE64 编码
    public static String getBASE64(String s) {
        if (s == null) return null;
        return Base64Utils.encodeToString(s.getBytes());
    }

}
